
//654.最大二叉树
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
    //使用递归来完成
    TreeNode* func(vector<int>& nums,int left,int right)
    {
        if(right<left) return nullptr;
        
        int pos=left;
        for(int i=left;i<=right;i++)  //找最大值
            if(nums[pos]<nums[i]) pos=i;
        TreeNode* root=new TreeNode(nums[pos]);
        root->left=func(nums,left,pos-1);   //创建左树
        root->right=func(nums,pos+1,right);   //创建右树

        return root;
    }
public:
    TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
        return func(nums,0,nums.size()-1);
    }
};